package middleware

import (
	"auth/config"
	"auth/constants"
	"auth/lib/authentication"
	"auth/store/redis"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

var whiteUrlMap map[string]struct{}

func InitWhiteUrlMap() {
	whiteUrlMap = make(map[string]struct{})
	for _, v := range config.Conf.WhiteUrl {
		whiteUrlMap[v] = struct{}{}
	}
	return
}

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {

		if _, ok := whiteUrlMap[c.Request.URL.Path]; ok {
			c.Next()
			return
		}

		// web操作直接下去
		os := c.GetHeader("source")
		if os == "app" {
			// token 认证
			token := c.GetHeader("Authorization")
			parts := strings.SplitN(token, " ", 2)
			if !(len(parts) == 2 && parts[0] == "Bearer") {
				c.JSON(http.StatusUnauthorized, nil)
				c.Abort()
				return
			}

			if opts, err := authentication.Extract(parts[1]); err != nil {
				c.JSON(http.StatusUnauthorized, nil)
				c.Abort()
				return
			} else {
				// 判断token是否过期
				result, _err := redis.KV.Get(c.Request.Context(), fmt.Sprintf("admin_token:%v", opts.UserID)).Result()
				if _err != nil || result == "" {
					c.JSON(http.StatusUnauthorized, nil)
					c.Abort()
					return
				}

				ctx := context.WithValue(c.Request.Context(), constants.UserId, opts.UserID)
				c.Request = c.Request.WithContext(ctx)
			}
			c.Next()
			return
		}

		// 设备端鉴权
		if os == "device" {

			c.Next()
			return
		}
		c.Next()

	}
}
